/**
 * Created by levy on 16/6/16.
 */
import {shopping} from "../const/shopping.js";
import {ItemUtil} from "../components/shopping/ItemUtil";
import RichText from "../components/RichText.js";
import TextDetail from "../components/detail/TextDetail.js";
import TipNum from "../components/TipNum";
import Img from "../components/Img";
import Radio from "../components/form/Radio";

const lf = liefeng,
    R = React,
    RC = React.createClass,
    ajax = lf.utils.ajax;

const goodsId = lf.utils.getUrlParam('goodsId');

const AttrDetail = RC({
    render() {
        const data = this.props.data;
        return (
            <div className="tab split-line border-bottom">
                <div className="title item-detail active border-bottom">商品详情</div>
                {
                    data.length ?
                        <TextDetail data={data} title="attrname" text="attrValue"
                                    addClass="text-left"/>
                        :
                        <div className="row light-gray">暂无</div>

                }
            </div>
        )
    }
});

/**
 * props:
 *  user
 */
const Root = RC({
    getInitialState() {
        return {
            itemDetail: {}, //商品基本信息
            attrDetail: [], //属性信息
            cartNum: '',
        }
    },
    getItemDetail() {
        ajax({
            url: shopping.api.prefix + shopping.api.itemDetail,
            data: {
                goodsId: goodsId
            },
            success: (data) => {
                if (data.code != 200) alert('没有商品数据');
                else {
                    this.setState({itemDetail: data.data});
                }
            }
        });
    },
    getAttrDetail() {
        ajax({
            url: shopping.api.prefix + shopping.api.attrDetail,
            data: {
                goodsId: goodsId
            },
        }, null, (data) => {

            this.setState({
                attrDetail: data,
            })
        });
    },
    getCartNum(user) {
        ajax({
            url: shopping.api.prefix + shopping.api.cart.getGoodsNum,
            data: {
                custGlobalId: user.globalId || (user.custLoginVo && user.custLoginVo.globalId),
            },
            success: function (data) {
                this.setState({cartNum: data.data});
            }.bind(this)
        });
    },
    componentWillMount() {
        let me = this,
            user = me.props.user;
        me.getCartNum(user);
      
        me.getItemDetail();
        
        me.getAttrDetail();

        lf.appJs.refresh((user) => {
            me.getCartNum(user);
        });
    },
    componentDidMount() {
        let $top = $(R.findDOMNode(this.refs.toTop));

        $(window).on('scroll', function () {
            if (document.body.scrollTop > 200) {
                $top.addClass('active');
            }
            else
                $top.removeClass('active');
        });

        $top.on('tap', () => {
            window.scrollTo(0, 0);
        });


        let $btns = $(R.findDOMNode(this.refs.btns));

        //查看购物车
        $btns.find('.shopping-cart').on('tap', () => {
            lf.appJs.doAction(`shopping-cart.html`, '购物车');
        });

        //添加到购物车
        $btns.find('.add-cart').on('tap', () => {
            ajax({
                type: 'POST',
                url: shopping.api.prefix + shopping.api.cart.addGoods,
                data: {
                    custGlobalId: this.props.user.globalId || (this.props.user.custLoginVo && this.props.user.custLoginVo.globalId),
                    goodsId: goodsId
                }
            }, null, (data) => {
                
                lf.appJs.toast('商品添加成功');
                
                this.getCartNum(this.props.user);
            })
        });

        //立即购买
        $btns.find('.buy-now').on('tap', () => {
            lf.appJs.doAction(`shopping-order-confirm.html?goodsId=${goodsId}`, '确认订单');
        });

    },
    renderRadio(attrList) {
        let titles = [],
            radio2DArray = [],
            index,
            tmpName;

        for (let i = 0, len = attrList.length; i < len; i++) {
            let attr = attrList[i];

            //多选的属性
            if (attr.attrType === 1) {

                if (tmpName != attr.attrName) {
                    tmpName = attr.attrName;
                    titles.push(tmpName);

                    if (typeof index === 'undefined') index = 0;
                    else index++;
                }

                if (!radio2DArray[index]) radio2DArray[index] = [];
                radio2DArray[index].push(attr.attrValue);
            }
        }

        return <div className="">
            {
                titles.map(function (title, i) {
                    return (
                        <div className="container block">
                            <p className={"title border-bottom"}>{title}</p>
                            <div className="radio-box border-bottom">
                                {radio2DArray[i].map(text =>
                                    <Radio text={text} name={title} selectCount="1"
                                           addClass="mui-icon mui-icon-checkmarkempty triangle"/>
                                )}
                            </div>
                        </div>
                    )
                })
            }
        </div>
    },
    render() {
        const data = this.state.itemDetail,
            imgStyle = {
                width: '100%',
                height: 'auto',
            },
            radios = this.renderRadio(this.state.attrDetail);

        let reg = /src="\//g,
            html = data.goodsDesc && data.goodsDesc.replace(reg, ('src="' + lf.utils.getProtocol() + shopping.imgPre));

        return <div className="shopping item-detail">
            <Img src={data.goodsImg ? lf.utils.getProtocol() + shopping.imgPre + data.goodsImg : ''}
                 style={{width: '100%',height:'3.75rem'}}/>
            <div className="container ">
                <p className="item-name">{data.goodsName || ''}</p>
            </div>
            <div className="container space-between">
                <div className="price-left">
                    <span className="sale-price num">{ItemUtil.getSalePrice(data)}</span>
                    <span className="origin-price num">{ItemUtil.getOriginPrice(data)}</span>
                </div>
                <div className="price-right">
                    <span className="shopping-red-bg">包邮</span>
                </div>
            </div>
            <div className="container space-between seller-promise">
                <div className="flex">
                    <span className="icon true-item"/>
                    <span>100%正品</span>
                </div>
                <div className="flex">
                    <span className="icon return-item"/>
                    <span>7天无理由退货</span>
                </div>
                <div className="flex">
                    <span className="icon cart"/>
                    <span>24小时内发货</span>
                </div>
            </div>
            {radios}
            <div className="container block ">
                <p className="title border-bottom">卖点</p>
                <div className="comment border-bottom">{data.goodsBrief || '暂无'}</div>
            </div>
            <AttrDetail data={this.state.attrDetail}/>
            <div className="img-detail">
                <p className="title border-bottom">图文详情</p>
                {
                    data.goodsDesc ?
                        <RichText text={html}/>
                        :
                        <div className="row light-gray">暂无</div>
                }
                <div className="img-list split-line after ele-hide">
                    <Img src={lf.imgUrl.none} style={imgStyle}/>
                </div>
            </div>
            <div className="btn-wrapper" ref="btns">
                <div className="fixed-btn flex space-between">
                    <div className="mui-btn shopping-blue-bg icon shopping-cart">
                        <TipNum num={this.state.cartNum}/>
                    </div>
                    <div>
                        <div className="mui-btn add-cart shopping-blue-bg">加入购物车</div>
                        <div className="mui-btn buy-now shopping-red-bg">立即购买</div>
                    </div>
                </div>
            </div>
            <div className="to-top mui-icon mui-icon-arrowup" ref="toTop"></div>
        </div>
    }
});

lf.appJs.getUser(function (user) {
    R.render(<Root user={user}/>, document.getElementById('root'));
});



